<?php
   
   function redirect( $step ) {
      header( "Location: ./index.php?step=$step" );
      exit();
   }
   
   // load framework
   require('../../libs/spf/SPF.php');
   
   try {
      
      define( 'SPF_APP_DIR', realpath('../../') );
      
      // load Smarty
      require(SPF_LIBS_DIR. '/smarty/Smarty.class.php');
      
      $smarty = new Smarty();
      $smarty->template_dir = realpath('.'). '/views/';
      $smarty->cache_dir    = realpath('.'). '/views/';
      $smarty->compile_dir  = realpath('.'). '/views/';
      
      // start the session
      SPF::$session = new SPF_Session();
      
      // load the configuration file if it exists
      if( file_exists(SPF_APP_DIR. '/config.php') )
         include(SPF_APP_DIR. '/config.php');
      else
         throw new SPF_Exception('Missing config file');
      
      // check for db connection
      if( $config['dsn'] ) {
         SPF::$db = SPF_Database::factory($config['dsn']);
         SPF::$db->fetch_mode = SPF_Database::FETCH_ASSOC;
      }
      
      // check for existing install
      $exists = SPF::$db->has_table('projects') && SPF::$db->has_table('tickets');
      
      // find out what the current step is and process it
      switch( SPF::get('step') ) {
         
         case 'user':
            
            $project_desc = SPF::$session->project_desc;
            
            $user = SPF::$session->user;
            if( $user === NULL )
               $user = array();
            
            // if form was submitted then validate inputs
            if( SPF::form_submitted('frm_install') ) {
            
               $user['user_name']    = SPF::post('user_name');
               $user['display_name'] = SPF::post('display_name');
               $user['email']        = SPF::post('email');
               $user['password']     = SPF::post('new_password');
               $user['confirm_pw']   = SPF::post('confirm_pw');
               $user['errors']       = array();
               
               if( !$user['user_name'] )
                  $user['errors']['user_name'] = SPF_Validator::ERR_MSG_REQUIRED;
               elseif( strlen($user['user_name']) < 3 )
                  $user['errors']['user_name'] = SPF_Validator::ERR_MSG_SHORT;
               elseif( !SPF_Validator::is_alphanumeric($user['user_name'], '_') )
                  $user['errors']['user_name'] = SPF_Validator::ERR_MSG_ALPHANUMERIC;
               
               if( !$user['display_name'] )
                  $user['errors']['display_name'] = SPF_Validator::ERR_MSG_REQUIRED;
               elseif( !SPF_Validator::is_alphanumeric($user['display_name'], ' ') )
                  $user['errors']['display_name'] = SPF_Validator::ERR_MSG_ALPHANUMERIC;
               
               if( !$user['email'] )
                  $user['errors']['email'] = SPF_Validator::ERR_MSG_REQUIRED;
               elseif( !SPF_Validator::is_email($user['email']) )
                  $user['errors']['email'] = SPF_Validator::ERR_MSG_EMAIL;
               
               if( !$user['password'] )
                  $user['errors']['password'] = SPF_Validator::ERR_MSG_REQUIRED;
               elseif( strlen($user['password']) < 5 )
                  $user['errors']['password'] = SPF_Validator::ERR_MSG_SHORT;
               elseif( !isset($user['errors']['password']) && ($user['password'] != $user['confirm_pw']) )
                  $user['errors']['confirm_pw'] = 'Passwords do not match.';
               
               if( !$user['errors'] ) {
                  $user['password'] = SPF::hash($user['password']);
                  unset($user['confirm_pw']);
                  SPF::$session->user = $user;
                  redirect('project');
               }
               
            }
            
            $smarty->assign('user', $user);
            $template = 'user';
            break;
         
         case 'project':
            
            $project_desc = SPF::$session->project_desc;
            
            if( SPF::form_submitted('frm_install') ) {
               
               $project_desc = SPF::post('project');
               
               if( !$project_desc )
                  $error = SPF_Validator::ERR_MSG_REQUIRED;
               elseif( strlen($project_desc) < 2 )
                  $error = SPF_Validator::ERR_MSG_SHORT;
               elseif( !SPF_Validator::is_alphanumeric($project_desc, ' ') )
                  $error = SPF_Validator::ERR_MSG_ALPHANUMERIC;
               
               if( !$error ) {
                  SPF::$session->project_desc = $project_desc;
                  redirect('settings');
               }
               
               $smarty->assign('project_error', $error);
               
            }
            
            $smarty->assign('project_desc', $project_desc);
            $template = 'project';
            break;
         
         case 'settings':
            
            $settings = SPF::$session->settings;
            if( $settings === NULL )
               $settings = array();
            
            // if form was submitted then validate inputs
            if( SPF::form_submitted('frm_install') ) {
            
               $settings['email_server']       = SPF::post('email_server');
               $settings['email_from']         = SPF::post('email_from');
               $settings['allow_registration'] = (int) SPF::post('allow_registration');
               $settings['auto_activation']    = (int) SPF::post('auto_activation');
               
               if( $settings['email_server'] && !SPF_Validator::is_ip($settings['email_server']) && gethostbyname($settings['email_server']) === $settings['email_server'] )
                  $settings['errors']['email_server'] = 'Unable to resolve host.';
               
               if( !$settings['errors'] ) {
                  SPF::$session->settings = $settings;
                  redirect('review');
               }
               
            } // form_submitted
            
            $template = 'settings';
            $smarty->assign('settings', $settings);
            break;
         
         case 'review':
            
            if( SPF::form_submitted('frm_install') )
               redirect('install');
               
            $smarty->assign('user', SPF::$session->user);
            $smarty->assign('project_desc', SPF::$session->project_desc);
            $smarty->assign('settings', SPF::$session->settings);
            $template = 'review';
            break;
         
         case 'install':
            $template = 'complete';
            install_db();
            $smarty->assign('install_dir', realpath('.'));
            SPF::$session->destroy();
            break;
         
         case 'welcome':
         default:
            if( SPF::form_submitted('frm_install') )
               redirect('user');
            
            $smarty->assign('exists', $exists);
      
            $template = 'welcome';
            break;
         
      } // switch $step
      
   }
   catch ( SPF_Database_Exception $error ) {
      $template = 'exception';
      $smarty->assign('exception_name', substr(get_class($error), 4, -10));
      $smarty->assign('exception', $error->to_array());
   }
   catch ( SPF_Exception $error ) {
      $template = 'exception';
      $smarty->assign('exception_name', substr(get_class($error), 4, -10));
      $smarty->assign('exception', $error->to_array());
   }
   
   if( $template )
      $smarty->display($template. '.tpl');
   
   function install_db() {
      
      $sql = "DROP TABLE IF EXISTS
                  comments,
                  components,
                  file_data,
                  file_header,
                  milestones,
                  projects,
                  registry,
                  ticket_history,
                  ticket_priority,
                  ticket_severity,
                  ticket_status,
                  ticket_type,
                  tickets,
                  users;";
      SPF::$db->execute($sql);

      $sql = "CREATE TABLE `comments` (
                 `id` int(10) unsigned NOT NULL auto_increment,
                 `ticket_id` int(10) unsigned NOT NULL default '0',
                 `created_user` varchar(15) NOT NULL default '',
                 `created_date` datetime NOT NULL default '0000-00-00 00:00:00',
                 `details` text NOT NULL,
                 PRIMARY KEY  (`id`)
               ) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `components` (
                 `id` int(10) unsigned NOT NULL auto_increment,
                 `project_id` int(10) unsigned NOT NULL default '0',
                 `description` varchar(45) NOT NULL default '',
                 `active` tinyint(3) unsigned NOT NULL default '1',
                 PRIMARY KEY  (`id`)
               ) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `file_data` (
                 `file_header_id` int(10) unsigned NOT NULL,
                 `file_content` mediumblob NOT NULL,
                 PRIMARY KEY  (`file_header_id`)
               ) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `file_header` (
                 `id` int(10) unsigned NOT NULL auto_increment,
                 `ticket_id` int(10) unsigned NOT NULL,
                 `file_name` varchar(45) NOT NULL,
                 `system_type` enum('IMAGE','PDF','TEXT','WORD','EXCEL','POWERPOINT','VISIO','ZIP','OTHER') NOT NULL default 'OTHER',
                 `mime_type` varchar(45) NOT NULL,
                 `upload_user` char(15) NOT NULL,
                 `upload_date` datetime NOT NULL,
                 `file_size` int(10) unsigned NOT NULL,
                 PRIMARY KEY  (`id`),
                 KEY `idx_ticket` (`ticket_id`)
               ) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `milestones` (
                 `id` int(10) unsigned NOT NULL auto_increment,
                 `project_id` int(10) unsigned NOT NULL default '0',
                 `description` varchar(45) NOT NULL default '',
                 `active` tinyint(3) unsigned NOT NULL default '1',
                 PRIMARY KEY  (`id`)
               ) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `projects` (
                 `id` int(10) unsigned NOT NULL auto_increment,
                 `description` varchar(45) NOT NULL default '',
                 `active` tinyint(3) unsigned NOT NULL default '1',
                 PRIMARY KEY  (`id`)
               ) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `registry` (
                 `var_name` char(100) NOT NULL,
                 `var_value` char(100) default NULL,
                 KEY `var_name` (`var_name`)
               ) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `ticket_history` (
                 `id` int(10) unsigned NOT NULL auto_increment,
                 `ticket_id` int(10) unsigned NOT NULL,
                 `modified_date` datetime NOT NULL,
                 `modified_by` varchar(45) NOT NULL,
                 `action_detail` varchar(255) NOT NULL,
                 PRIMARY KEY  (`id`),
                 KEY `idx_date` (`ticket_id`,`modified_date`)
               ) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `ticket_priority` (
                 `id` int(10) unsigned NOT NULL auto_increment,
                 `description` varchar(45) NOT NULL default '',
                 `active` tinyint(3) unsigned NOT NULL default '1',
                 PRIMARY KEY  (`id`)
               ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `ticket_severity` (
                 `id` int(10) unsigned NOT NULL auto_increment,
                 `description` varchar(45) NOT NULL default '',
                 `active` tinyint(3) unsigned NOT NULL default '1',
                 PRIMARY KEY  (`id`)
               ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `ticket_status` (
                 `id` int(10) unsigned NOT NULL auto_increment,
                 `description` varchar(45) NOT NULL default '',
                 `active` tinyint(3) unsigned NOT NULL default '1',
                 `system_type` enum('OPEN','CLOSED') NOT NULL default 'OPEN',
                 PRIMARY KEY  (`id`)
               ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `ticket_type` (
                 `id` int(10) unsigned NOT NULL auto_increment,
                 `description` varchar(45) NOT NULL default '',
                 `active` tinyint(3) unsigned NOT NULL default '1',
                 PRIMARY KEY  (`id`)
               ) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `tickets` (
                 `id` int(10) unsigned NOT NULL auto_increment,
                 `project_id` int(10) unsigned NOT NULL default '0',
                 `component_id` int(10) unsigned NOT NULL default '0',
                 `milestone_id` int(10) unsigned NOT NULL default '0',
                 `ticket_type_id` int(10) unsigned NOT NULL default '0',
                 `ticket_status_id` int(10) unsigned NOT NULL default '0',
                 `ticket_severity_id` int(10) unsigned NOT NULL default '0',
                 `ticket_priority_id` int(10) unsigned NOT NULL default '0',
                 `assigned_user` varchar(15) NOT NULL default '',
                 `created_user` varchar(15) NOT NULL default '',
                 `created_date` datetime NOT NULL default '0000-00-00 00:00:00',
                 `modified_user` char(15) NOT NULL,
                 `modified_date` datetime NOT NULL,
                 `title` varchar(255) NOT NULL,
                 `details` mediumtext NOT NULL,
                 PRIMARY KEY  (`id`)
               ) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "CREATE TABLE `users` (
                 `user_name` varchar(15) NOT NULL default '',
                 `password` varchar(32) NOT NULL default '',
                 `display_name` varchar(45) NOT NULL default '',
                 `email` varchar(100) NOT NULL default '',
                 `user_status` enum('NOT_ACTIVATED','ACTIVE','DELETED') NOT NULL default 'NOT_ACTIVATED',
                 `is_admin` tinyint(1) NOT NULL DEFAULT '0',
                 PRIMARY KEY  (`user_name`)
               ) ENGINE=MyISAM DEFAULT CHARSET=latin1;";
      SPF::$db->execute($sql);
      
      $sql = "INSERT INTO `ticket_priority` (`id`,`description`,`active`) VALUES 
                (1,'Low',1),
                (2,'Normal',1),
                (3,'High',1),
                (4,'Immediate',1);";
      SPF::$db->execute($sql);
      
      $sql = "INSERT INTO `ticket_severity` (`id`,`description`,`active`) VALUES 
                (1,'Trivial',1),
                (2,'Minor',1),
                (3,'Major',1),
                (4,'Critical',1);";
      SPF::$db->execute($sql);
      
      $sql = "INSERT INTO `ticket_status` (`id`,`description`,`active`,`system_type`) VALUES 
             (1,'Open',1,'OPEN'),
             (2,'In Progress',1,'OPEN'),
             (3,'Closed',1,'CLOSED');";
      SPF::$db->execute($sql);
      
      $sql = "INSERT INTO `ticket_type` (`id`,`description`,`active`) VALUES 
                (1,'Bug',1),
                (2,'Question',1),
                (3,'Request',1),
                (4,'Task',1);";
      SPF::$db->execute($sql);
      
      $settings = SPF::$session->settings;
      $sql = "INSERT INTO `registry` (`var_name`,`var_value`) VALUES 
                ('mail.server','{$settings['email_server']}'),
                ('mail.from','{$settings['email_from']}'),
                ('users.auto_activation','{$settings['auto_activation']}'),
                ('users.allow_registration','{$settings['allow_registration']}');";
      SPF::$db->execute($sql);
      
      $project_desc = SPF::$session->project_desc;
      $sql = "INSERT INTO `projects` (`id`,`description`,`active`) VALUES 
                (1,'{$project_desc}',1);";
      SPF::$db->execute($sql);
            
      $user = SPF::$session->user;
      $sql = "INSERT INTO `users` (`user_name`,`password`,`display_name`,`email`,`user_status`, `is_admin`) VALUES 
                ('{$user['user_name']}','{$user['password']}','{$user['display_name']}','{$user['email']}','ACTIVE', 1);";
      SPF::$db->execute($sql);
      
      // fetch data from session
      
   } // install_db
   
?>
